import Vue from 'vue';
import MessageBoxVue from './message-box.vue';
import RcUtil from '@/utils'

let MessageBoxConstructor = Vue.extend(MessageBoxVue);

let MessageBox = (options) => {
    let instance = new MessageBoxConstructor({
        el: document.createElement('div')
    });
    for (var prop in options) {
        if (options.hasOwnProperty(prop)) {
            instance[prop] = options[prop];
        }
    }
    document.body.appendChild(instance.$el);
    Vue.nextTick(() => {
        instance.showBox = true;
    });
    return instance;
};

// 确认框
MessageBox.confirm = (options) => {
    var defaultOpts = {
            showCancelBtn: true,
            title: '',
            content: '请输入提示内容',
            contentType: 'text',
            okVal: '确定',
            ok() {},
            cancelVal: '取消',
            cancel() {},
            close() {}
        },
        opts = {};
    if (!RcUtil.isPlainObject(options)) {
        return false;
    }
    opts = RcUtil.extend(true, defaultOpts, options);
    if (typeof navigator !== 'undefined' && navigator.notification) {
        navigator.notification.confirm(opts.content, (buttonIndex) => {
            if (buttonIndex == '2') {
                if (typeof opts.ok === 'function') {
                    opts.ok()
                }
            } else {
                if (typeof opts.cancel === 'function') {
                    opts.cancel()
                }
            }
            if (typeof opts.close === 'function') {
                opts.close()
            }
        }, opts.title, [opts.cancelVal, opts.okVal]);
    } else {
        return MessageBox(opts);
    }
}

// 提示框
MessageBox.alert = (options) => {
    var defaultOpts = {
            title: '',
            content: '请输入提示内容',
            okVal: '确定',
            ok() {},
            close() {}
        },
        opts = {};
    if (RcUtil.isString(options)) {
        opts = RcUtil.extend(true, defaultOpts, {
            content: options
        });
    } else {
        opts = RcUtil.extend(true, defaultOpts, options);
    }
    if (typeof navigator !== 'undefined' && navigator.notification) {
        navigator.notification.alert(opts.content, () => {
            if (typeof opts.ok === 'function') {
                opts.ok()
            }
            if (typeof opts.close === 'function') {
                opts.close()
            }
        }, opts.title, opts.okVal);

    } else {
        return MessageBox(opts);
    }
}

export default MessageBox;
export {
    MessageBox
}